<script setup lang="ts">

import { message } from 'ant-design-vue';
import { PropType, ref } from 'vue';
import { FileModel } from '../model/model';
import { sendCommand } from '../utils/TauriUtils';
import { open } from '@tauri-apps/api/shell';

const props = defineProps({
    dataList: Array as PropType<Array<FileModel>>
});

const emit = defineEmits<{
    (e: 'startDel', allFlag: Boolean): void
}>()

//console.log("dataList: ", props.dataList);

const columns = [
    {
        title: '文件名',
        dataIndex: 'name',
        key: 'name',
        width: "20%"
    },
    {
        title: '大小',
        dataIndex: 'sizeStr',
        key: 'sizeStr',
        width: "10%"
    },
    {
        title: '数量',
        dataIndex: 'num',
        key: 'num',
        width: "5%"
    },
    {
        title: '位置',
        key: 'path',
        dataIndex: 'path',
        width: "35%"
    },
    {
        title: '操作',
        key: 'action',
        width: "13%"
    },
];
const fileDataList = ref<FileModel[]>(props.dataList!);

const showDetailsView = ref(false);
const selectFileModel = ref<FileModel | undefined>();

const showDetail = (item: FileModel) => {
    //console.log("item: ", item);
    showDetailsView.value = true;
    selectFileModel.value = item;
}

const removePathItem = async (delPath: string) => {
    let newModel = selectFileModel.value?.pathArray.filter(i => i != delPath);
    if (newModel) {
        try {
            await sendCommand('delete_file', { filepath: delPath });
            selectFileModel.value!.path = newModel.join(", ");
            selectFileModel.value!.pathArray = newModel;
            message.success('删除成功');
        } catch (e: any) {
            message.error(e.toString());
        }

    }
}

const delFileModelConfirm = async (item: FileModel) => {
    //console.log("delFileModel: ", item);
    try {
        await sendCommand('delete_file_list', { filepath: item.pathArray });
        fileDataList.value = fileDataList.value.filter(i => i.md5 != item.md5);
        message.success('删除成功');
    } catch (e) {
        message.error('删除失败 ' + e);
    }
};

const delFileModelCancel = (e: MouseEvent) => {
    //console.log(e);
    message.warn('已取消');
};

const openFile = async (filepath: string) => {
    if (filepath.startsWith("/")) {
        let index = filepath.lastIndexOf("/");
        await open(filepath.substring(0, index));
    } else {
        let index = filepath.lastIndexOf("\\");
        await open(filepath.substring(0, index));
    }
}

const delButtonCancel = (e: MouseEvent) => {
    console.log("delButtonCancel");
};

const delAllFile = async (allFlag: boolean) => {
    console.log("delAllFile, ", allFlag);
    const deleteArray = getDeleteFilePath(fileDataList.value, allFlag);
    console.log("array: ", deleteArray);
    await sendCommand("delete_all", {
        allFlag : allFlag,
        delFile: deleteArray
    });
    message.info("正在删除...");
    emit('startDel', allFlag);
}

const getDeleteFilePath = (list: FileModel[], allFlag: boolean): string[] => {
    if(allFlag) {
       return list.flatMap(i => i.pathArray);
    }

    return list.flatMap(i => {
        return i.pathArray.slice(1);
    });
}
</script>

<template>
    <div v-if="fileDataList.length > 0" style="margin-bottom: 10px; margin-top:20px;">
        <a-popconfirm placement="topLeft" ok-text="删除" cancel-text="再想想" @confirm="delAllFile(true)"
            @cancel="delButtonCancel">
            <template #title>
                <p>该操作会删除全部文件，包含原文件，且此操作不可逆，</p>
                <p>被删除的文件不会进入回收站，请谨慎操作</p>
              </template>
            <a-button class="fileList" type="primary" danger>删除全部</a-button>
        </a-popconfirm>
        <a-popconfirm placement="topLeft" ok-text="删除" cancel-text="再想想" @confirm="delAllFile(false)"
            @cancel="delButtonCancel">
            <template #title>
                <p>该操作会删除全部重复的副本文件，</p>
                <p>只保留最初的原文件，此操作不可逆，请谨慎操作</p>
              </template>
            <a-button danger>删除重复副本</a-button>
        </a-popconfirm>
    </div>

    <a-table v-if="fileDataList.length > 0" class="fileList" :columns="columns" :data-source="fileDataList" bordered>
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
                <a @click="showDetail(record)">
                    {{ record.name }}
                </a>
            </template>

            <template v-else-if="column.key === 'action'">
                <span>
                    <a-popconfirm title="确定要删除该文件所有的重复文件吗?" ok-text="确定" cancel-text="再想想"
                        @confirm="delFileModelConfirm(record)" @cancel="delFileModelCancel">
                        <a>删除</a>
                    </a-popconfirm>
                    <a-divider type="vertical" />
                    <a @click="showDetail(record)">查看</a>
                </span>
            </template>
        </template>
    </a-table>

    <a-modal v-model:visible="showDetailsView" width="70%" :footer="null">
        <a-descriptions title="详细内容" bordered>
            <a-descriptions-item label="文件名称">{{ selectFileModel?.name }}</a-descriptions-item>
            <a-descriptions-item label="文件大小">{{ selectFileModel?.sizeStr }}</a-descriptions-item>
            <a-descriptions-item label="文件重复数量">{{ selectFileModel?.num }}</a-descriptions-item>
            <a-descriptions-item label="文件MD5" :span="3">{{ selectFileModel?.md5 }}</a-descriptions-item>
            <a-descriptions-item label="文件列表" :span="3">
                <a-list :data-source="selectFileModel?.pathArray">
                    <template #renderItem="{ item }">
                        <a-list-item>
                            <div> {{ item }}</div>
                            <template #actions>
                                <a @click="openFile(item)">查看</a>
                                <a-popconfirm title="确定要删除该文件吗?" ok-text="确定" cancel-text="再想想"
                                    @confirm="removePathItem(item)" @cancel="delFileModelCancel">
                                    <a>删除</a>
                                </a-popconfirm>

                            </template>
                        </a-list-item>
                    </template>
                </a-list>
            </a-descriptions-item>
        </a-descriptions>

    </a-modal>


</template>

<style scoped>
.fileList {
    margin: 0 20px;
}
</style>